package com.esoon.api;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.util.Log;

import com.esoon.smartsee.R;
import com.mb.mediaengine.MediaEngineAudioWrapper;
import com.mb.mediaengine.MediaEngineDataBase;
import com.mb.mediaengine.MediaEngineVideoDB;
import com.mb.mediaengine.MediaEngineVideoWrapper;
import com.mb.smartsee.utils.MBLocal;
import com.mb.voip.api.MBVoipClientApp;
import com.mb.voip.api.VTCallStateListener;
import com.mb.voip.api.VideoPhone;
import com.mb.voip.config.VoipConfigLoad;
import com.mb.voip.utils.Utils;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by Administrator on 2018\5\23 0023.
 */

public class SmartSeeImpl implements SmartSeeInterface {
    private static final String TAG = "SmartSeeImpl";
    VoipConfigLoad config;
    private static int[] videobandwidthValue = {128000, 256000, 384000, 512000, 768000, 1024000,
            1500000, 2000000, 2500000, 3000000, 4000000, 8000000};
    private static int[] transportTypeValue = {0, 1, 2};
    private static int[] natValue = {0, 1};
    private static int[] encryptValue = {0, 1, 2};
    private static boolean[] videopackageValue = {false, true};
    private static String[] h264profileValue = {"0", "1", "2", "3", "4", "5", "6", "7"};

    @Override


    public void ESClientInitialize(Activity activity, String server, String username, String port, VTCallStateListener vtCallStateListener) {


        Log.e("SmartImpl", "server is :" + server);
        Log.e("SmartImpl", "port is :" + port);
        Log.e("SmartImpl", "username is :" + username);

        MediaEngineVideoWrapper.LoadLayoutAndBitrate();
        Utils.ConfigAutoStartMediaConfigXML(false, activity.getApplicationContext(),
                R.raw.mediaconfig);
        try {
            String prefix = activity.getFilesDir().getPath() + "/";
            MediaEngineVideoDB.mediafilePrefix = prefix;
        } catch (Exception el) {
            el.printStackTrace();
        }

        MBVoipClientApp clientApp = MBVoipClientApp.getVoipClientApp();
        config = VoipConfigLoad.GetConfigInstance();
        MediaEngineVideoWrapper videoWrapper = MediaEngineVideoWrapper.getMediaEngineVideoWrapper();
        MediaEngineAudioWrapper audioWrapper = MediaEngineAudioWrapper.getMediaEngineAudioWrapper();

        videoWrapper.LoadDefaultVideoQualityValues();

        try {
            config.ConfigAutoStart(activity.getApplicationContext(),
                    R.raw.mbvoipclient);
            //载入请求检测函数
            Utils.ConfigAutoStart(false, activity.getApplicationContext(),
                    R.raw.posedbraw);


            String localip = MBLocal.getMyIpFromIP();
            config.mStorage.setLocalIp(localip);
            config.updateConfig();
            //更新配置信息
        } catch (Exception ex) {
            Log.e(TAG, "VoipConfig Exception = " + ex.getMessage());


        }

        config.mStorage.setAuthUsername(username);
        config.mStorage.setUserName(username);
        config.mStorage.setDisplayUserName(username);
        config.mStorage.setPassword(username);
        config.mStorage.setDomainName(server);
        config.mStorage.setRegistrarIp(server);
        config.mStorage.setRegistrarPort(port);
        config.mStorage.setOutboundProxyName("");
        config.mStorage.setOutboundProxyPort("0");
        config.mStorage.setEncryptType(encryptValue[0]);
        config.mStorage.setDataPresentation(false);
        config.mStorage.setTransportType(transportTypeValue[0]);
        config.mStorage.setNatPass(natValue[1]);
        config.mStorage.setVideoLocalProfileLevel(h264profileValue[3]);
        config.mStorage.setVideoPackage(videopackageValue[0]);
        config.mStorage.setVideoEncodeTargetBitRate("" + videobandwidthValue[5], false);
        config.mStorage.setVideoEncodeTargetBitRate("" + videobandwidthValue[5], true);


        config.updateConfig();


        VideoPhone vt = VideoPhone.getVideoPhone();
        String prefix = activity.getFilesDir().getPath();
        vt.setConfigFilePathPrefix(prefix);
        vt.wrapperInitMediaEngineLib();
        MediaEngineDataBase.bEnableLog = true;
        vt.LogEnable(MediaEngineDataBase.bEnableLog);
        AudioManager am = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
        int mode = am.getMode();
        audioWrapper.CreateMediaEngine(activity, am);
        audioWrapper.ConfigAudioConfig();
        videoWrapper.setVideoCodecParameter();
        am.setMode(mode);
        clientApp.RegisterPhoneStateCallback(vtCallStateListener);
        int res = clientApp.InitVoipClient();
        res = clientApp.ConfigVoipClient();
        res = clientApp.StartVoipClient();
        res = clientApp.register();


    }

    @Override
    public void ESClientUploadFile(String Url, int port, File file, String userId) {
        int seqId = 1;
        SimpleDateFormat ft = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
        RequestParams requestParams = new RequestParams("http://" + Url + ":" + port + "/user/upload");
        requestParams.addHeader("type", "face_0");
        requestParams.addHeader("seqId", String.valueOf(seqId));
        requestParams.addHeader("userid", userId);
        requestParams.addHeader("uploadTime", ft.format(new Date()));
        requestParams.addBodyParameter("file", file);
        Log.e("SmartseeImpl","请求体："+requestParams.toString());
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                Log.e("SmartseeImpl", "上传成功" + result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("SmartseeImpl", "上传失败" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

        seqId++;
    }


}